package com.jarpackage.ui;

import com.jarpackage.config.AppConfig;
import com.jarpackage.config.RepositoryConfig;
import com.jarpackage.model.Dependency;
import com.jarpackage.service.BatchImportService;
import com.jarpackage.service.RepositoryService;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javafx.geometry.Pos;

public class MainWindow {
    private final Stage stage;
    private final AppConfig appConfig;
    private final TextField groupIdField;
    private final TextField artifactIdField;
    private final TextField versionField;
    private final TextField downloadPathField;
    private final TextArea logArea;
    private final TextArea batchImportArea;
    private final BatchImportService batchImportService;

    public MainWindow(Stage stage, AppConfig appConfig) {
        this.stage = stage;
        this.appConfig = appConfig;
        this.batchImportService = new BatchImportService();

        // 设置全局样式变量
        String primaryColor = "#1976d2";
        String secondaryColor = "#f8f9fa";
        String borderColor = "#dee2e6";
        String textColor = "#495057";
        String labelStyle = String.format("-fx-font-family: 'Microsoft YaHei'; -fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: %s;", textColor);
        String textFieldStyle = String.format("-fx-background-color: white; -fx-border-color: %s; -fx-border-radius: 4; -fx-padding: 8 12; -fx-font-size: 13px; -fx-font-family: 'Microsoft YaHei';", borderColor);
        String buttonStyle = String.format("-fx-background-color: %s; -fx-text-fill: white; -fx-font-size: 13px; -fx-padding: 8 20; -fx-background-radius: 4; -fx-font-family: 'Microsoft YaHei'; -fx-cursor: hand; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 4, 0, 0, 1);", primaryColor);
        String secondaryButtonStyle = String.format("-fx-background-color: %s; -fx-text-fill: %s; -fx-font-size: 13px; -fx-padding: 8 20; -fx-background-radius: 4; -fx-border-color: %s; -fx-border-radius: 4; -fx-font-family: 'Microsoft YaHei'; -fx-cursor: hand;", secondaryColor, textColor, borderColor);

        // 创建主布局
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(15));
        root.setStyle("-fx-background-color: #ffffff;");
        
        // 创建选项卡面板
        TabPane tabPane = new TabPane();
        tabPane.setStyle("-fx-background-color: transparent; -fx-tab-min-height: 28px; -fx-tab-max-height: 28px;");

        // 设置选项卡
        Tab settingsTab = new Tab("设置");
        settingsTab.setClosable(false);
        settingsTab.setStyle(labelStyle);
        VBox settingsContent = new VBox(15);
        settingsContent.setPadding(new Insets(20));
        settingsContent.setStyle("-fx-background-color: white; -fx-background-radius: 8px;");

        // 创建仓库配置部分
        Label repositoryLabel = new Label("Maven 仓库设置");
        repositoryLabel.setStyle("-fx-font-family: 'Microsoft YaHei'; -fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #2c3e50;");
        GridPane repositoryForm = new GridPane();
        repositoryForm.setHgap(8);
        repositoryForm.setVgap(8);
        repositoryForm.setPadding(new Insets(5));

        TextField urlField = new TextField();
        TextField usernameField = new TextField();
        PasswordField passwordField = new PasswordField();

        String textFieldStyle1 = "-fx-background-color: white; -fx-border-color: #e9ecef; -fx-border-radius: 4; -fx-padding: 6 8; -fx-font-size: 13px; -fx-font-family: 'Microsoft YaHei';";
        urlField.setStyle(textFieldStyle1);
        usernameField.setStyle(textFieldStyle1);
        passwordField.setStyle(textFieldStyle1);

        if (!appConfig.getRepositories().isEmpty()) {
            RepositoryConfig repo = appConfig.getRepositories().get(0);
            urlField.setText(repo.getUrl());
            usernameField.setText(repo.getUsername());
            passwordField.setText(repo.getPassword());
        }

        repositoryForm.add(new Label("URL:"), 0, 0);
        repositoryForm.add(urlField, 1, 0);
        repositoryForm.add(new Label("Username:"), 0, 1);
        repositoryForm.add(usernameField, 1, 1);
        repositoryForm.add(new Label("Password:"), 0, 2);
        repositoryForm.add(passwordField, 1, 2);

        // 创建其他设置部分
        Label settingsLabel = new Label("Settings:");
        settingsLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #333;");
        GridPane settingsForm = new GridPane();
        settingsForm.setHgap(10);
        settingsForm.setVgap(5);
        settingsForm.setPadding(new Insets(5));

        CheckBox downloadDependenciesCheckBox = new CheckBox("Download Dependencies");
        CheckBox validateChecksumCheckBox = new CheckBox("Validate Checksum");

        downloadDependenciesCheckBox.setSelected(appConfig.getSettings().isDownloadDependencies());
        validateChecksumCheckBox.setSelected(appConfig.getSettings().isValidateChecksum());

        settingsForm.add(downloadDependenciesCheckBox, 0, 0);
        settingsForm.add(validateChecksumCheckBox, 0, 1);

        // 创建保存按钮
        String buttonsStyle = "-fx-background-color: #1976d2; -fx-text-fill: white; -fx-font-size: 14px; -fx-padding: 8 20; -fx-border-radius: 4;";
        Button saveButton = new Button("保存配置");
        saveButton.setStyle(buttonsStyle);
        saveButton.setOnAction(e -> saveSettings(urlField, usernameField, passwordField, downloadDependenciesCheckBox, validateChecksumCheckBox));

        // 创建按钮容器并设置居中对齐
        HBox saveButtonBox = new HBox(saveButton);
        saveButtonBox.setAlignment(Pos.CENTER);
        saveButtonBox.setPadding(new Insets(20, 0, 0, 0));

        settingsContent.getChildren().addAll(
            repositoryLabel,
            repositoryForm,
            settingsLabel,
            settingsForm,
            saveButtonBox
        );
        settingsTab.setContent(settingsContent);
        
        // 调整按钮布局为居中
        HBox buttonBox = new HBox(15);
        buttonBox.setPadding(new Insets(20, 0, 0, 0));
        buttonBox.setAlignment(Pos.CENTER);

        // 单个下载选项卡
        Tab singleDownloadTab = new Tab("单个下载");
        singleDownloadTab.setStyle(labelStyle);
        singleDownloadTab.setClosable(false);
        VBox singleDownloadContent = new VBox(15);
        singleDownloadContent.setPadding(new Insets(20));
        singleDownloadContent.setStyle("-fx-background-color: white;");

        // 创建输入表单
        GridPane form = new GridPane();
        form.setHgap(15);
        form.setVgap(15);
        form.setPadding(new Insets(10));

        // 添加表单字段
        groupIdField = new TextField();
        groupIdField.setPromptText("例如: com.example");
        groupIdField.getStyleClass().add("text-field");

        artifactIdField = new TextField();
        artifactIdField.setPromptText("例如: my-library");
        artifactIdField.getStyleClass().add("text-field");

        versionField = new TextField();
        versionField.setPromptText("例如: 1.0.0");
        versionField.getStyleClass().add("text-field");
        downloadPathField = new TextField();
        
        // 设置文本框样式
        groupIdField.setStyle(textFieldStyle);
        artifactIdField.setStyle(textFieldStyle);
        versionField.setStyle(textFieldStyle);
        downloadPathField.setStyle(textFieldStyle);

        if (appConfig.getDefaultDownloadPath() != null) {
            downloadPathField.setText(appConfig.getDefaultDownloadPath());
        }

        // 设置标签样式
        Label groupIdLabel = new Label("groupId:");
        Label artifactIdLabel = new Label("artifactId:");
        Label versionLabel = new Label("version:");
        Label downloadPathLabel = new Label("下载路径:");
        
        groupIdLabel.setStyle(labelStyle);
        artifactIdLabel.setStyle(labelStyle);
        versionLabel.setStyle(labelStyle);
        downloadPathLabel.setStyle(labelStyle);

        form.add(groupIdLabel, 0, 0);
        form.add(groupIdField, 1, 0);
        form.add(artifactIdLabel, 0, 1);
        form.add(artifactIdField, 1, 1);
        form.add(versionLabel, 0, 2);
        form.add(versionField, 1, 2);
        form.add(downloadPathLabel, 0, 3);

        // 创建下载路径选择器
        HBox pathBox = new HBox(10);
        Button browseButton = new Button("浏览");
        browseButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #333; -fx-border-color: #ddd; -fx-border-radius: 4; -fx-padding: 8 15;");
        browseButton.setOnAction(e -> selectDownloadPath());
        pathBox.getChildren().addAll(downloadPathField, browseButton);
        form.add(pathBox, 1, 3);

        // 创建按钮
        HBox buttonBox1 = new HBox(15);
        buttonBox1.setPadding(new Insets(20, 0, 0, 0));
        Button downloadButton = new Button("下载");
        downloadButton.setStyle(buttonsStyle);
        buttonBox.getChildren().addAll(downloadButton);
        buttonBox.setAlignment(Pos.CENTER);

        // 设置按钮事件
        downloadButton.setOnAction(e -> downloadArtifact());

        singleDownloadContent.getChildren().addAll(form, buttonBox);
        singleDownloadTab.setContent(singleDownloadContent);

        // 批量下载选项卡
        Tab batchDownloadTab = new Tab("批量下载");
        batchDownloadTab.setStyle(labelStyle);
        batchDownloadTab.setClosable(false);
        VBox batchDownloadContent = new VBox(15);
        batchDownloadContent.setPadding(new Insets(20));
        batchDownloadContent.setStyle("-fx-background-color: white;");

        Label batchInstructionLabel = new Label("请按照格式输入依赖: groupId,artifactId,version (每行一个)");
        batchInstructionLabel.setStyle(labelStyle);
        
        batchImportArea = new TextArea();
        batchImportArea.setPrefRowCount(5);
        batchImportArea.setPromptText("com.example,library-name,1.0.0");
        batchImportArea.setStyle(String.format("-fx-background-color: white; -fx-border-color: %s; -fx-border-radius: 4; -fx-padding: 8; -fx-font-family: 'Microsoft YaHei'; -fx-font-size: 13px;", borderColor));

        HBox batchPathBox = new HBox(10);
        TextField batchDownloadPathField = new TextField();
        batchDownloadPathField.setStyle(textFieldStyle);
        
        if (appConfig.getDefaultDownloadPath() != null) {
            batchDownloadPathField.setText(appConfig.getDefaultDownloadPath());
        }
        
        Button batchBrowseButton = new Button("浏览");
        batchBrowseButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #333; -fx-border-color: #ddd; -fx-border-radius: 4; -fx-padding: 8 15;");
        
        Label batchPathLabel = new Label("下载路径:");
        batchPathLabel.setStyle(labelStyle);
        
        batchBrowseButton.setOnAction(e -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择下载目录");
            directoryChooser.setTitle("选择下载目录");
            File selectedDirectory = directoryChooser.showDialog(stage);
            if (selectedDirectory != null) {
                batchDownloadPathField.setText(selectedDirectory.getAbsolutePath());
            }
        });
        batchPathBox.getChildren().addAll(batchPathLabel, batchDownloadPathField, batchBrowseButton);

        Button batchDownloadButton = new Button("全部下载");
        batchDownloadButton.setStyle(buttonsStyle);
        HBox batchButtonBox = new HBox(15);
        batchButtonBox.getChildren().add(batchDownloadButton);
        batchButtonBox.setAlignment(Pos.CENTER);
        batchButtonBox.setPadding(new Insets(20, 0, 0, 0));

        batchDownloadButton.setOnAction(e -> batchDownload(batchDownloadPathField.getText()));

        batchDownloadContent.getChildren().addAll(
            batchInstructionLabel,
            batchImportArea,
            batchPathBox,
            batchButtonBox
        );
        batchDownloadTab.setContent(batchDownloadContent);

        tabPane.getTabs().addAll(settingsTab, singleDownloadTab, batchDownloadTab);

        // 创建日志区域
        logArea = new TextArea();
        logArea.setEditable(false);
        logArea.setPrefRowCount(8);
        logArea.setStyle("-fx-background-color: white; -fx-border-color: #e9ecef; -fx-border-radius: 4; -fx-padding: 5; -fx-font-family: 'Consolas'; -fx-font-size: 13px;");

        // 组装界面
        VBox mainContent = new VBox(8);
        mainContent.getChildren().addAll(tabPane, logArea);
        root.setCenter(mainContent);

        // 设置场景
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/styles/main.css").toExternalForm());
        stage.setTitle("Jar包快速拉取工具");
        stage.setScene(scene);
        stage.setMinWidth(600);
        stage.setMinHeight(500);
    }

    private void batchDownload(String downloadPath) {
        if (downloadPath.isEmpty()) {
            showError("验证错误", "请选择下载路径");
            return;
        }

        String input = batchImportArea.getText().trim();
        if (input.isEmpty()) {
            showError("验证错误", "请输入依赖信息");
            return;
        }

        File downloadDir = new File(downloadPath);
        if (!downloadDir.exists() && !downloadDir.mkdirs()) {
            showError("错误", "无法创建下载目录");
            return;
        }

        List<Dependency> dependencies = batchImportService.parseDependencies(input);
        if (dependencies.isEmpty()) {
            showError("验证错误", "未找到有效的依赖");
            return;
        }

        if (!appConfig.getRepositories().isEmpty()) {
            RepositoryService repositoryService = new RepositoryService(appConfig.getRepositories().get(0));
            ProgressDialog progressDialog = new ProgressDialog(stage, "批量下载");
            progressDialog.show();

            new Thread(() -> {
                int total = dependencies.size();
                int current = 0;
                for (Dependency dependency : dependencies) {
                    try {
                        progressDialog.updateStatus("正在下载 " + dependency + "...");
                        File downloadedFile = repositoryService.downloadArtifact(dependency, downloadPath);
                        current++;
                        double progress = (double) current / total;
                        progressDialog.updateProgress(progress);
                        Platform.runLater(() -> logArea.appendText("下载成功，保存至: " + downloadedFile.getAbsolutePath() + "\n"));
                    } catch (IOException ex) {
                        Platform.runLater(() -> logArea.appendText("下载 " + dependency + " 时出错: " + ex.getMessage() + "\n"));
                    }
                }
                Platform.runLater(() -> {
                    progressDialog.updateStatus("下载完成");
                    progressDialog.close();
                });
            }).start();
        } else {
            showError("配置错误", "未配置仓库信息");
        }
    }

    private void selectDownloadPath() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择下载目录");
        if (downloadPathField.getText() != null && !downloadPathField.getText().isEmpty()) {
            File initialDirectory = new File(downloadPathField.getText());
            if (initialDirectory.exists()) {
                directoryChooser.setInitialDirectory(initialDirectory);
            }
        }

        File selectedDirectory = directoryChooser.showDialog(stage);
        if (selectedDirectory != null) {
            downloadPathField.setText(selectedDirectory.getAbsolutePath());
            appConfig.setDefaultDownloadPath(selectedDirectory.getAbsolutePath());
            try {
                appConfig.save("config.json");
            } catch (IOException ex) {
                showError("保存配置出错", ex.getMessage());
            }
        }
    }

    private void downloadArtifact() {
        String groupId = groupIdField.getText().trim();
        String artifactId = artifactIdField.getText().trim();
        String version = versionField.getText().trim();
        String downloadPath = downloadPathField.getText().trim();

        if (groupId.isEmpty() || artifactId.isEmpty() || version.isEmpty() || downloadPath.isEmpty()) {
            showError("验证错误", "请填写所有字段");
            return;
        }

        File downloadDir = new File(downloadPath);
        if (!downloadDir.exists() && !downloadDir.mkdirs()) {
            showError("错误", "无法创建下载目录");
            return;
        }

        Dependency dependency = new Dependency(groupId, artifactId, version);
        if (!appConfig.getRepositories().isEmpty()) {
            RepositoryService repositoryService = new RepositoryService(appConfig.getRepositories().get(0));
            ProgressDialog progressDialog = new ProgressDialog(stage, "下载");
            progressDialog.show();

            new Thread(() -> {
                try {
                    progressDialog.updateStatus("正在下载 " + dependency + "...");
                    progressDialog.updateProgress(-1); // 使用不确定进度
                    File downloadedFile = repositoryService.downloadArtifact(dependency, downloadPath);
                    Platform.runLater(() -> {
                        progressDialog.updateProgress(1);
                        progressDialog.updateStatus("下载完成");
                        logArea.appendText("下载成功，保存至: " + downloadedFile.getAbsolutePath() + "\n");
                        progressDialog.close();
                    });
                } catch (IOException ex) {
                    Platform.runLater(() -> {
                        showError("下载错误", ex.getMessage());
                        logArea.appendText("错误: " + ex.getMessage() + "\n");
                        progressDialog.close();
                    });
                }
            }).start();
        } else {
            showError("配置错误", "未配置仓库信息");
        }
    }

    private void openSettings() {
        SettingsDialog dialog = new SettingsDialog(stage, appConfig);
        dialog.showAndWait();
    }

    private void showError(String title, String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle(title);
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        });
    }

    private void saveSettings(TextField urlField, TextField usernameField, PasswordField passwordField,
                            CheckBox downloadDependenciesCheckBox, CheckBox validateChecksumCheckBox) {
        // 保存仓库配置
        RepositoryConfig repositoryConfig = new RepositoryConfig();
        repositoryConfig.setUrl(urlField.getText().trim());
        repositoryConfig.setUsername(usernameField.getText().trim());
        repositoryConfig.setPassword(passwordField.getText());

        appConfig.getRepositories().clear();
        appConfig.getRepositories().add(repositoryConfig);

        // 保存其他设置
        appConfig.getSettings().setDownloadDependencies(downloadDependenciesCheckBox.isSelected());
        appConfig.getSettings().setValidateChecksum(validateChecksumCheckBox.isSelected());

        try {
            appConfig.save("config.json");
            logArea.appendText("配置已保存\n");
        } catch (IOException ex) {
            showError("保存配置出错", ex.getMessage());
        }
    }

    public void show() {
        stage.show();
    }
}